package com.saifan.wyy_ov.ui.onlishop;

import java.util.ArrayList;
import java.util.List;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.data.bean.CartBean;
import com.saifan.wyy_ov.data.bean.CartBean.GoodsList;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.data.bean.OrderBean;
import com.saifan.wyy_ov.data.bean.Orderdetail;
import com.saifan.wyy_ov.data.bean.SubmitOrderBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.MaterialDialog;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.PriceUtils;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;

public class MyCartOrderActivity extends BaseActivity {
    private android.support.v7.widget.Toolbar toolbar;
    private com.saifan.wyy_ov.ui.view.NoScrollListView listView;
    private TextView tv_allTotal;
    private TextView tv_tel;
    private TextView tv_store_assess;
    private TextView tv_address;
    private MaterialDialog addressDialog, telDialog;
    private EditText editTel, editaddress;
    OrderBean orderBean;
    GetData getData;
    Gson gson;
    double total = 0;
    // 从购物车跳转过来传的数据 是一个List<CartBean> 的json;
    String cartBeansjson;
    List<CartBean> cartBeans;
    List<GoodsList> goodsLists = new ArrayList<GoodsList>();
    private ArrayList<OrderBean> orderBeans;
    static int CHANGETOTAL = 12;
    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == CHANGETOTAL) {
                double v = (double) msg.obj;
                total += v;
                tv_allTotal.setText(PriceUtils.getPrice(total) + " 元");
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        cartBeansjson = getIntent().getStringExtra("cartBeans");
        cartBeans = new Gson().fromJson(cartBeansjson, new TypeToken<List<CartBean>>() {
        }.getType());
        setContentView();

        bindContent();
        gson = new Gson();
        getData = new GetData();
    }

    public void bindContent() {
        // 展开购物车的每一项商品显示到listview中.
        for (CartBean cartBean : cartBeans) {

            for (GoodsList goodsList : cartBean.getGoodsList()) {
                if (goodsList.isIspay()) {
                    goodsLists.add(goodsList);
                    total += (goodsList.getGoodsPrice() * goodsList.getCount());
                }
            }
        }
        AdapterSubmitItem adapterSubmitItem = new AdapterSubmitItem(goodsLists, this, handler);
        tv_allTotal.setText(PriceUtils.getPrice(total) + "元");
        listView.setAdapter(adapterSubmitItem);
        adapterSubmitItem.notifyDataSetChanged();
    }

    public void unbindContent() {
        // 从listview中取出goodslist装回给购物车.
        for (CartBean cartBean : cartBeans) {
            for (GoodsList goodsList : cartBean.getGoodsList()) {
                for (GoodsList bean : goodsLists) {
                    if (goodsList.getShoppingCartID() == bean.getShoppingCartID()) {
                        goodsList = bean;
                    }
                }
            }
        }
    }

    private void setContentView() {
        setContentView(R.layout.activity_mycart_order);
        addressDialog = new MaterialDialog(this);
        telDialog = new MaterialDialog(this);
        toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        listView = (com.saifan.wyy_ov.ui.view.NoScrollListView) findViewById(R.id.list);
        tv_allTotal = (TextView) findViewById(R.id.tv_allTotal);
        tv_tel = (TextView) findViewById(R.id.tv_tel);
        tv_store_assess = (TextView) findViewById(R.id.tv_store_assess);
        tv_address = (TextView) findViewById(R.id.tv_address);
        tv_address.setText(StringUtil.returnShow(getRoomInfoBean().getXMDA_XMMC() + getRoomInfoBean().getWYFJDA_FJMC()));
        tv_tel.setText(StringUtil.returnShow(getRoomInfoBean().getWYKHDA_SJ()));
    }

    public void submitOrder(View view) {
        view.setEnabled(false);
        buildOrders();
        getData.getDataJson(this, Api.GroupBuy.SUBMITORDER, orderBeans, "正在提交,请稍候!", new ResponseData() {
            @Override
            public void onSuccess(String json) {
                delCat();

                List<SubmitOrderBean> list = gson.fromJson(json, new TypeToken<List<SubmitOrderBean>>() {
                }.getType());
                if (list != null && list.size() > 0) {
                    Intent intentGoPayActivity = new Intent(MyCartOrderActivity.this, PayActivity.class);
                    double total = 0;
                    for (SubmitOrderBean submitOrderBean : list) {
                        total += Double.valueOf(submitOrderBean.getAmount());
                    }
                    int paymentWay = 2;
                    intentGoPayActivity.putExtra("paymentWay", paymentWay);
                    intentGoPayActivity.putExtra("total", total);
                    intentGoPayActivity.putExtra("SubmitOrderBeans", json);
                    finish();
                    startActivity(intentGoPayActivity);
                } else {
                    LogUtil.i(json);
                }
            }

            @Override
            public void onFailed(String str) {
                LogUtil.e(str);
            }
        });
    }

    public void buildOrders() {
        orderBeans = new ArrayList<OrderBean>();
        unbindContent();
        for (CartBean cartBean : cartBeans) {
            OrderBean orderBean = new OrderBean();
            orderBean.setAddress(tv_address.getText().toString());
            orderBean.setContact(getRoomInfoBean().getWYKHDA_KHMC());
            orderBean.setOrderPeopleID(getRoomInfoBean().getWYKHDA_ZJ());
            orderBean.setUserID(cartBean.getStoreID() + "");
            orderBean.setTel(tv_tel.getText().toString());
            ArrayList<Orderdetail> orderdetails = new ArrayList<Orderdetail>();
            for (GoodsList goodsList : cartBean.getGoodsList()) {
                if (goodsList.isIspay()) {
                    Orderdetail orderdetail = new Orderdetail();
                    orderdetail.setCount(goodsList.getCount());
                    orderdetail.setPrice(Double.valueOf(goodsList.getGoodsPrice()));
                    orderdetail.setUserID(cartBean.getStoreID() + "");
                    orderdetail.setType(0);
                    orderdetail.setGoodsID(goodsList.getGoodsID() + "");
                    orderdetail.setGoodsName(goodsList.getGoodsName());
                    orderdetail.setCoverPhoto(goodsList.getCoverPhoto());
                    orderdetail.setNote(goodsList.getNote());
                    orderdetails.add(orderdetail);
                }
            }
            if (!orderdetails.isEmpty()) {
                orderBean.setOrderdetail(orderdetails);
                orderBeans.add(orderBean);
            }
        }
    }

    public void changeAddress(View view) {
        // TODO Auto-generated method stub
        if (addressDialog != null) {
            View editView = getLayoutInflater().from(this).inflate(R.layout.address_edit, null);
            editaddress = (EditText) editView.findViewById(R.id.edit_address);
            addressDialog.setView(editView).
                    setPositiveButton("是", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            tv_address.setText(editaddress.getText().toString());
                            addressDialog.dismiss();
                        }
                    }).setNegativeButton("否", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    addressDialog.dismiss();
                }
            }).setCanceledOnTouchOutside(false)
                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }
                    }).show();
        }
    }

    public void changeTel(View view) {
        // TODO Auto-generated method stub
        if (telDialog != null) {
            View editView = getLayoutInflater().from(this).inflate(R.layout.tel_edit, null);
            editTel = (EditText) editView.findViewById(R.id.edit_tel);
            telDialog.setView(editView).
                    setPositiveButton("是", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            tv_tel.setText(editTel.getText().toString());
                            telDialog.dismiss();
                        }
                    }).setNegativeButton("否", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    telDialog.dismiss();
                }
            }).setCanceledOnTouchOutside(false)
                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(DialogInterface dialog) {
                        }
                    }).show();
        }
    }


    public void delCat() {

        for (GoodsList goodsList : goodsLists) {
            CommonDataBean commonDataBean = new CommonDataBean();
            commonDataBean.setID(goodsList.getID());
            commonDataBean.setShoppingCartID(goodsList.getShoppingCartID());
            GetData getData = new GetData();
            getData.getDataJson(this, Api.GroupBuy.DELETESHOPPINGCART, commonDataBean, "", new ResponseData() {
                @Override
                public void onSuccess(String json) {

                }

                @Override
                public void onFailed(String str) {

                }
            });

        }


    }

}
